package net.learntechnology.examples.servlet;

import com.ibatis.common.jdbc.ScriptRunner;
import com.ibatis.common.resources.Resources;
import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Web application lifecycle listener.
 * @author nmaves
 */

public class DatabaseInitializer implements ServletContextListener {

	private static final Log   log     = LogFactory.getLog(DatabaseInitializer.class);

    public void contextInitialized(ServletContextEvent contextEvent) {
        try {

			Properties dbProps = Resources.getResourceAsProperties("ibatis/db.properties");

            Reader reader = Resources.getResourceAsReader("ddl/initDB.sql");

			log.debug("Loading driver : " + dbProps.getProperty("driver"));
            Class.forName(dbProps.getProperty("driver"));

			log.debug("Connection to : " + dbProps.getProperty("jdbcURL"));
            Connection connection = DriverManager.getConnection(dbProps.getProperty("jdbcURL"), dbProps.getProperty("username"), dbProps.getProperty("password"));

            ScriptRunner runner = new ScriptRunner(connection, true, true);

            runner.runScript(reader);

        } catch (SQLException ex) {
            contextEvent.getServletContext().log("Error creating DB", ex);
        } catch (ClassNotFoundException ex) {
            contextEvent.getServletContext().log("Could not load JDBC Driver", ex);
        } catch (IOException ex) {
            contextEvent.getServletContext().log("Error reading init files", ex);
        }
    }

    public void contextDestroyed(ServletContextEvent contextEvent) {

        try {
			Properties dbProps = Resources.getResourceAsProperties("ibatis/db.properties");
            Connection connection = DriverManager.getConnection(dbProps.getProperty("jdbcURL"), dbProps.getProperty("username"), dbProps.getProperty("password"));
            PreparedStatement statement = connection.prepareStatement("SHUTDOWN");
            statement.execute();
        } catch (SQLException ex) {
            contextEvent.getServletContext().log("Error shutting down DB", ex);
        } catch (IOException ex) {
            contextEvent.getServletContext().log("Error reading properties", ex);
        }
    }
}